var socket = null;
var array = new Array();
var myMap=new Map();
var num = 9;

function connect(){
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        socket = new WebSocket("ws://127.0.0.1:8555/stock/websocket/22");
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");

            $("#status").html("已连接...");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            var obj = JSON.parse(msg.data);
            myMap.set(obj.stockCode,obj);
            buildStockList(obj);
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
            $("#status").html("未连接...");
            socket = null;
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }
    }
}

connect();

function buildStockList(obj) {
    var appendDiv =
        '<div id="'+obj.stockCode+'" style="float:left;padding-left: 10px;border:1px solid #F00;">\n' +
        '    <div style="float:left;">'+obj.stockCode+'</div>\n' +
        '    <div id="display_'+obj.stockCode+'" style="float:left;padding-left: 5px" onclick="display(this)"><a href="javasript:;">查看</a></div>\n' +
        '    <div id="del_'+obj.stockCode+'" style="float:left;padding-left: 5px" onclick="del(this)"><a href="javasript:;">删除</a></div>\n' +
        '</div>';
    $("#stocklist").append(appendDiv);
    buildPic(obj);
}

function display(elm){
    console.log(elm.id);
    var id = elm.id.replace("display_","");
    var obj = myMap.get(id);
    buildPic(obj);
}

function del(elm){
    console.log(elm.id);
    var id = elm.id.replace("del_","");
    //myMap.remove(id);
    $("#"+id).remove();
    var obj = myMap.get(id);

    //buildPic(obj);
}

function buildPic(obj){
    if(array.length == num){
        array.shift();
    }
    array.push(obj);
    for(var i = 0;i<array.length;i++){
        var index = array.length<num?num-1-i:i;
        var id = "d"+index;
        console.log(id);
        document.getElementById(id).style.backgroundImage="url("+array[i].url+")";
    }
}

$(document).ready(function(){
    //循环执行，每隔1秒钟执行一次 2000
    var t1=window.setInterval(refreshCount, 2000);
    function refreshCount() {
        for(var i = 0;i<array.length;i++){
            var index = array.length<num?num-1-i:i;
            var id = "d"+index;
            document.getElementById(id).style.backgroundImage="url("+array[i].url+")";
        }
    }
});





